#include "anchorroom.h"
#include "ui_anchorroom.h"
#include "hallwidget.h"
#include "userinfo.h"
#include "audioout.h"
#include "audioin.h"
#include <QMessageBox>

#define CameraCpatureRate 30 //frames per sec


AnchorRoom::AnchorRoom(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::AnchorRoom)
{
    ui->setupUi(this);

    ui->labvideo->setScaledContents(true);

    QString curUser = SingleTon<UserInfo>::getReference().getUsername();
    this->setWindowTitle(curUser);

    initCameraVideoSet();
    screen = QApplication::primaryScreen();
    process = new QProcess(this);
    CaptureRate = new QTimer(this);

}

AnchorRoom::~AnchorRoom()
{
    animations.clear();
    delete ui;
    delete screen;
    delete curCamera;
    delete imgcap;
    delete CaptureRate;
    delete process;
}

//摄像头直播方式控制
void AnchorRoom::on_rbcamera_clicked(bool checked)
{
    if(checked){
        ui->rbdesktop->setChecked(0);
        on_rbdesktop_clicked(0);
        startCameraVideo();
    }
    else
    {stopCameraVideo();}
}
//全屏直播方式控制
void AnchorRoom::on_rbdesktop_clicked(bool checked)
{
    if(checked){
        ui->rbcamera->setChecked(0);
        on_rbcamera_clicked(0);
        startDeskVideo();
    }
    else
    {stopDeskVideo();}
}

void AnchorRoom::showCamera(const QByteArray &data)
{
    showImg(data);
}

void AnchorRoom::showImg(const QByteArray &data)
{
    QPixmap p;
    p.loadFromData(data);
    ui->labvideo->setPixmap(p);
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//摄像头直播
void AnchorRoom::initCameraVideoSet()
{
    QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
    if(cameras.size()>0){
        initCamera();
        initImgcap();
    }else {
        QMessageBox("camera","no camera",QMessageBox::Critical,0,1,1,this);
        qDebug()<<"no camera";
        return;
    }

    connect(imgcap,&QCameraImageCapture::imageCaptured,
            this,&AnchorRoom::on_imgcaptured);
}

//摄像头初始化
void AnchorRoom::initCamera()
{
    QCameraInfo curCameraInfo = QCameraInfo::defaultCamera();//获取缺省摄像头
    curCamera = new QCamera(curCameraInfo,this);
    if(curCamera->isCaptureModeSupported(QCamera::CaptureStillImage))
    {
        qDebug()<<"support still Capture";
        curCamera->setCaptureMode(QCamera::CaptureStillImage);
    }
}
//摄像头截图初始化
void AnchorRoom::initImgcap()
{
    imgcap = new QCameraImageCapture(curCamera,this);
    imgcap->setBufferFormat(QVideoFrame::Format_Jpeg);
    if(imgcap->isCaptureDestinationSupported(QCameraImageCapture::CaptureToBuffer))
    {
        qDebug()<<"support buffer";
        imgcap->setCaptureDestination(QCameraImageCapture::CaptureToBuffer);
    }
}

void AnchorRoom::CaptureCamera()
{
    imgcap->capture("./test.jpg");
}
//摄像头截图
void AnchorRoom::on_imgcaptured(int id, QImage img)
{
    Q_UNUSED(id);

    imgbuffer.open(QIODevice::WriteOnly | QIODevice::Truncate);
//    img.scaled(200,150).save(&imgbuffer,"JPG");
    img.save(&imgbuffer,"JPG",50);
    imgbuffer.close();
    ClientHandlerVideoTrans::transfer(imgbuffer.data());
}
//全屏截图
void AnchorRoom::CaptureScreen()
{
    imgbuffer.open(QIODevice::WriteOnly | QIODevice::Truncate);
    screen->grabWindow(0).save(&imgbuffer,"JPG",30);
    imgbuffer.close();
    ClientHandlerVideoTrans::transfer(imgbuffer.data());
}

void AnchorRoom::startDeskVideo()
{
    QStringList args;
    args << "tv://";
    process->start("mplayer", args); //启动该进程，并传入参数args

    connect(CaptureRate,&QTimer::timeout,
            this,&AnchorRoom::CaptureScreen);
    CaptureRate->start(1000/CameraCpatureRate);
}

void AnchorRoom::stopDeskVideo()
{
    process->kill();
    disconnect(CaptureRate,&QTimer::timeout,
            this,&AnchorRoom::CaptureScreen);
    CaptureRate->stop();
    ui->labvideo->clear();
}

void AnchorRoom::startCameraVideo()
{
    connect(CaptureRate,&QTimer::timeout,
            this,&AnchorRoom::CaptureCamera);
    curCamera->start();
    CaptureRate->start(1000/CameraCpatureRate);
}

void AnchorRoom::stopCameraVideo()
{
    disconnect(CaptureRate,&QTimer::timeout,
            this,&AnchorRoom::CaptureCamera);
    CaptureRate->stop();
    curCamera->stop();
    ui->labvideo->clear();
}

//---------------------------------------------------------------------------
//--------------------------------------------------------------
//创建房间
void AnchorRoom::createRoom(QString& anchor, QString& roomid)
{
    show();
    clearlist();
    setRoom(anchor,roomid);
    addAudience(anchor);
    ui->chkbarrage->setChecked(true);
}
//加入房间
void AnchorRoom::joinRoom(QString& anchor, QString& roomid)
{
    show();
    clearlist();
    setRoom(anchor,roomid);
    ui->chkMIC->setDisabled(true);
    ui->chkbarrage->setChecked(true);
    ui->rbcamera->setDisabled(true);
    ui->rbdesktop->setDisabled(true);
}
//设置房间
void AnchorRoom::setRoom(QString& anchor, QString& roomid)
{
    //设置不能直接关闭
    SingleTon<UserInfo>::getReference().notcloseable();
    Anchor = anchor;
    RoomID = roomid;
    ui->labanchor->setText("roomid : "+roomid);
    ui->labname->setText("anchor : "+Anchor);
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//刷新观众列表
void AnchorRoom::addAudience(QString audi)
{
    ui->listWidget->addItem(audi);
}
void AnchorRoom::deleAudience(QString& audi)
{
    //遍历listwidget中内容,找到相应观众
    int count = ui->listWidget->count();
    for(int i=0; i < count;++i)
    {
        if( audi == ui->listWidget->item(i)->text())
        {
            QListWidgetItem *item = ui->listWidget->takeItem(i);
            delete item;
        }
    }
}
void AnchorRoom::clearlist()
{
    ui->listWidget->clear();
}


//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//关闭房间
void AnchorRoom::on_actionQuit_triggered()
{
    SingleTon<AnchorRoom>::getReference().close();
}

//关闭
void AnchorRoom::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    if(!SingleTon<UserInfo>::getReference().ifcloseable()){

        ClientHandlerCloseRoom::transfer();

    }
    SingleTon<hallWidget>::getReference().show();

}

//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//发送聊天
void AnchorRoom::on_pushButton_clicked()
{
    QString text = ui->lineEdit->text();
    if(text.isEmpty()) {return;}
    ClientHandlerChat::transfer(text);
    ui->lineEdit->clear();
}
void AnchorRoom::on_lineEdit_returnPressed()
{
    on_pushButton_clicked();
}

//聊天
void AnchorRoom::appendText(const QString& text)
{
    ui->plainTextEdit->appendPlainText(text);
}
//弹幕
void AnchorRoom::appendbarrage(QString& message)
{
    if(!ui->chkbarrage->isChecked()){
        return;
    }

    QLabel *barrage = new QLabel(message,this);
    barrage->setWindowFlags(Qt::WindowStaysOnTopHint);
    QPalette pe;
    //设置黑底红字
    pe.setColor(QPalette::Background,Qt::black);
    pe.setColor(QPalette::WindowText,Qt::red);
    barrage->setPalette(pe);

    //设置字体
    QFont font;
    font.setFamily(QStringLiteral("幼圆"));
    font.setPixelSize(15);

    barrage->setFont(font);
    barrage->adjustSize();
    barrage->show();

    //使用动画,变化属性为坐标位置
    QPropertyAnimation *animation = new QPropertyAnimation(barrage, "pos");
    animations.push_back(animation);
    animation->setDuration(5000);
    int posY = ui->labvideo->y()+(++barragecount%20)*15;
    animation->setStartValue(QPoint(ui->labvideo->x()+400,posY));
    animation->setEndValue(QPoint(ui->labvideo->x(),posY));
    animation->start();
    //设置信号槽,在动画结束时释放内存
     connect(animation,&QPropertyAnimation::finished,
             [=](){
         animations.removeOne(animation);
         barrage->clear();
         barrage->deleteLater();
         animation->deleteLater();
     });
}
//关闭弹幕
void AnchorRoom::on_chkbarrage_clicked(bool checked)
{
    if(!checked)
    {
        for(auto i : animations)
        {emit i->finished();}
    }
    barragecount=0;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//开麦
void AnchorRoom::on_chkMIC_clicked(bool checked)
{
    if(checked)
    {SingleTon<audioIn>::getReference().record_start();}
    else
    {SingleTon<audioIn>::getReference().record_stop();}
}

//静音
void AnchorRoom::on_chkmute_clicked(bool checked)
{
    if(checked)
    {SingleTon<audioOut>::getReference().play_stop();}
    else
    {SingleTon<audioOut>::getReference().play_start();}
}




